/**
 * 开单人额度设置 编辑页
 *
 * 作者 zhangwei
 * 日期 2024-08-30 09:28:03
 */
layui.use(['jquery','febs', 'form','laydate', 'table','validate','autocomplete'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        table = layui.table,
        laydate = layui.laydate,
        $view = $('#incentiveQuotaConfig-edit'),
        $addBtn = $view.find("#addBtn"),
        $addGoods = $('#addGoods'),
        validate = layui.validate,
        tableIns;

    var tenantId = POPUP_DATA.tenantId;
    var goodsList = [];
    var initCount = 0;

    laydate.render({
        elem: "#year",
        type: "year",
        trigger:'click',
        showBottom:false
    })

    form.verify(validate);
    form.render();



    initFormValue();
    function initFormValue() {
        if (incentiveQuotaConfigData) {
            form.val("incentiveQuotaConfig-edit-form", {
                "quotaConfigId": incentiveQuotaConfigData.quotaConfigId,
                "tenantId": incentiveQuotaConfigData.tenantId,
                "year": incentiveQuotaConfigData.year,
                "userId": incentiveQuotaConfigData.userId,
                "userNo": incentiveQuotaConfigData.userNo,
                "realName": incentiveQuotaConfigData.realName,
                "deptId": incentiveQuotaConfigData.deptId,
                "deptName": incentiveQuotaConfigData.deptName,
                "penaltyBonusRatio": incentiveQuotaConfigData.penaltyBonusRatio,
                "totalQuota": incentiveQuotaConfigData.totalQuota,
                "rewardedQuota": incentiveQuotaConfigData.rewardedQuota,
                "goodsRewardFlg": incentiveQuotaConfigData.goodsRewardFlg == '1'? true:false,
                "topFlg": incentiveQuotaConfigData.topFlg == '1'? true:false,
                "status": incentiveQuotaConfigData.status == '1'? true:false ,
            });
            $('#hideInfoDiv').removeClass('febs-hide');
            $('#userNoDiv').text(incentiveQuotaConfigData.userNo == ''? '--':incentiveQuotaConfigData.userNo);
            $('#deptNameDiv').text(incentiveQuotaConfigData.deptName == ''?'--':incentiveQuotaConfigData.deptName);
            goodsList = incentiveQuotaConfigData.goodsList;
            if(incentiveQuotaConfigData.goodsRewardFlg == '1'){
                $("#quotaGoodsDiv").removeClass("febs-hide");
                initQuotaGoodsTable();
            }
        }
    }

    function initQuotaGoodsTable() {
        initCount ++;
        tableIns = febs.table.init({
            elem: $view.find('table'),
            id: 'quotaGoodsTable',
            page:false,
            skin: '',
            limit:Number.MAX_VALUE,
            cols: [[
                {title: '序号', type: 'numbers',width: 80},
                {field:'goodsId',title: 'id',hide:true},
                {field:'filePath',title: 'filePath',hide:true},
                // {field:'smallPath',title: '图片',align:'center',  minWidth: 150},
                {field: 'smallPath', title: '奖品图片', width: 120, align: 'center', templet: function (d) {
                     var img = '<img class="tupian" style="width: 60px;height: 25px;" src="' + ctx + d.smallPath + '" ' +
                     'data-bigsrc="' + ctx + d.filePath + '"  lay-event="imgEvent" /></img>';
                     return img;
                    }
                },
                {field:'goodsName',title: '奖品名称',align:'left',  minWidth: 120},
                {field:'goodsPrice',title: '单价',align:'center',width:100},
                {field:'goodsUnit',title: '单位',align:'center',width:100},
                {title: '操作',align:'center',toolbar: '#quotaGoods-option', width: 80}
            ]],
            data:goodsList
        });
    }

    $('#realName').autocomplete({
        serviceUrl: ctx + 'common/user/list',//测试接口
        paramName:'keywords',
        useType:'user',
        params:{ tenantId: currentTenantId},
        onSelect: function(suggestion) {
            $view.find("input[name=realName]").val(suggestion.value);
            $view.find('input[name="userId"]').val(suggestion.data)
            $view.find('input[name="deptId"]').val(suggestion.deptId);
            $view.find('input[name="userNo"]').val(suggestion.userNo);
            $('#deptName').val(suggestion.deptName);
            $('#hideInfoDiv').removeClass('febs-hide');
            if(suggestion.userNo){
                $('#userNoDiv').text(suggestion.userNo);
            }else{
                $('#userNoDiv').text('--');
            }
            if(suggestion.deptId){
                $('#deptNameDiv').text(suggestion.deptName);
            }else{
                $('#deptNameDiv').text('--');
            }
        },
    });

    $addBtn.on('click', function () {
        febs.modal.open('选择用户', 'common/hazardType', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['90%', '85%'],
            data:{
                tenantId:tenantId,
                multiple:false,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                temp = selectData;
                console.log("获得的人员"+JSON.stringify(temp))
                // debugger

                if(selectData){
                    $view.find('input[name="userId"]').val(selectData.userId);
                    $view.find('input[name="realName"]').val(selectData.uname);
                    $('#hideInfoDiv').removeClass('febs-hide');
                    if(selectData.userNo){
                        $('#userNo').val(selectData.userNo);
                        $('#userNoDiv').text(selectData.userNo);
                    }else {
                        $('#userNo').val('');
                        $('#userNoDiv').text('--');
                    }
                    if(selectData.deptId){
                        $('#deptName').val(selectData.deptName);
                        $('#deptNameDiv').text(selectData.deptName);
                        $view.find('input[name="deptId"]').val(selectData.deptId);
                    }else {
                        $('#deptName').val('');
                        $('#deptNameDiv').text('--');
                        $view.find('input[name="deptId"]').val('');
                    }
                    layer.close(index);
                }

            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });

    $addGoods.on('click', function () {
        febs.modal.open('奖品选择', 'common/goods', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:tenantId,
                selectList:goodsList,
                multiple:true,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                for (var i = 0; i < selectData.length; i++) {
                    var temp = {};
                    temp.goodsId = selectData[i].goodsId;
                    temp.smallPath = selectData[i].smallPath;
                    temp.filePath = selectData[i].smallPath;
                    temp.goodsName = selectData[i].goodsName;
                    temp.goodsPrice = selectData[i].goodsPrice;
                    temp.goodsUnit = selectData[i].goodsUnit;
                    if(isRepeat(goodsList,selectData[i].goodsId)){
                        febs.alert.warn("奖品"+selectData[i].goodsName+"已添加!");
                        return false;
                    }
                    goodsList.push(temp);
                }
                console.log(goodsList);
                reloadTab(goodsList);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });

    });

    table.on('tool(quotaGoodsTable)', function (obj) {
        var data = obj.data,
            that = this,
            tr = obj.tr,
            layEvent = obj.event;
        if (layEvent === 'del') {
            febs.modal.confirm('删除', '确定删除？', function (index) {
                var cacheData = layui.table.cache['quotaGoodsTable'];//获取缓存
                obj.del();//①移除这一行
                var rowIndex = obj.tr.attr("data-index"); //获取行索引
                cacheData.splice(rowIndex, 1);  //②彻底移除元素，从缓存里移除这一行
                goodsList = cacheData;
                reloadTab(goodsList);

                layer.close(index);//关闭弹窗
            });
        }
    });

    function reloadTab(data){
        tableIns.reload({data:data});
    }

    function isRepeat(arr,goodsId) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i]['goodsId'] === goodsId) {
                return true;
            }
        }
        return false;
    }

    form.on('submit(incentiveQuotaConfig-edit-form-submit)', function (data) {
        addOrUpdate(data.field);
        return false;
    });

    function addOrUpdate(data) {
        data.tenantId = tenantId;
        if(data.status == 'on'){
            data.status = "1";
        }else{
            data.status = "0";
        }
        if(data.userNo == '--'){
            data.userNo = '';
        }
        if(data.deptName == '--'){
            data.deptName = '';
        }
        if(data.goodsRewardFlg == 'on'){
            data.goodsRewardFlg = "1";
        }else{
            data.goodsRewardFlg = "0";
            goodsList = [];
        }
        data.goodsList = goodsList;
        console.log(data);
        febs.modal.confirm('保存提示', "是否保存额度设置？",function (index) {
            if (data.quotaConfigId && data.quotaConfigId.length > 0) {
                febs.postArray(ctx + 'incentiveQuotaConfig/update', data, function () {
                    layer.closeAll();
                    febs.alert.success('修改成功');
                    $('#febs-incentiveQuotaConfig').find('#query').trigger('click');
                });
            } else {
                febs.postArray(ctx + 'incentiveQuotaConfig', data, function () {
                    layer.closeAll();
                    febs.alert.success('新增成功');
                    $('#febs-incentiveQuotaConfig').find('#query').trigger('click');
                });
            }
        })
    }

    function deleteAllRows(){
        let data = layui.table.cache['quotaGoodsTable'];//获取缓存
        if(data.length>1){
            for(let i=data.length-1;i>=0;i--){
                data.splice(i,1);
            }
            reloadTab(data);
        }
    }

    // 状态 - 开关操作 是否选择
    form.on('switch(goodsRewardFlg)', function(data){
        console.log(initCount);
        let status = data.elem.checked;
        if(status){
            $("#quotaGoodsDiv").removeClass("febs-hide");
            if(initCount<1){
                initQuotaGoodsTable();
                initCount ++;
            }
        }else{
            $("#quotaGoodsDiv").addClass("febs-hide");
            deleteAllRows();
        }
    });
});